from flask import Flask, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from config import Config
import logging
from logging.handlers import RotatingFileHandler
import os

# 初始化扩展
db = SQLAlchemy()

def create_app(config_class=Config):
    app = Flask(__name__,
                template_folder='templates',    
                static_folder='static',
                static_url_path='/static')  # 明确指定静态文件URL路径
    
    # 添加调试路由
    @app.route('/debug/static')
    def debug_static():
        import os
        static_dir = app.static_folder
        files = []
        for root, dirs, filenames in os.walk(static_dir):
            for filename in filenames:
                files.append(os.path.join(root, filename))
        return {'static_folder': static_dir, 'files': files}
    
    # 添加字体文件路由
    @app.route('/static/fonts/<path:filename>')
    def serve_font(filename):
        return send_from_directory(os.path.join(app.root_path, 'static', 'fonts'), filename)
    
    app.config.from_object(config_class)

    # 启用文件系统缓存
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 604800  # 1周
    
    # 压缩响应
    if not app.debug:
        from flask_compress import Compress
        Compress(app)

    # 初始化扩展
    db.init_app(app)

    with app.app_context():
        # 创建数据库表
        db.create_all()

    # 注册蓝图
    from app.routes import main
    app.register_blueprint(main)

    # 配置日志
    if not app.debug:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/pixel_forge.log', maxBytes=10240, backupCount=10)
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
        ))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
        app.logger.setLevel(logging.INFO)
        app.logger.info('Pixel Forge startup')

    return app 